package com.tcoiss.webservice.utils;

import com.google.gson.Gson;
import com.tcoiss.common.core.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Set;

/**welxop
 * */
@Component
public class UrlConnectionUtils {
    public String requestGetData(String urlHander, HashMap<String,String> params){
        HttpURLConnection conn = null;
        InputStream is = null;
        String data = "";
        String paramStr = createEncodeUrlByParams(params);
        if(StringUtils.isNotBlank(paramStr)){
            urlHander = urlHander + "?" + paramStr;
        }
        try {
            URL url = new URL(urlHander);
            conn = createConnection(url,conn,false);
            is = conn.getInputStream();
            data = getDataStringByInputStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != conn){
                conn.disconnect();
            }
        }
        return data;
    }
    public String requestPostData(String urlHander, HashMap<String,String> params){
        HttpURLConnection conn = null;
        InputStream is = null;
        String paramStr = createEncodeUrlByParams(params);
        String data = "";
        if(StringUtils.isNotBlank(paramStr)){
            urlHander = urlHander + "?" + paramStr;
        }

        try {
            URL url = new URL(urlHander);
            conn = createConnection(url,conn,true);
            is = conn.getInputStream();
            data = getDataStringByInputStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != conn){
                conn.disconnect();
            }
        }
        return data;
    }

    public InputStream uploadData(String urlHander, HashMap<String,String> params){
        HttpURLConnection conn = null;
        InputStream is = null;
        String paramStr = createEncodeUrlByParams(params);
        String data = "";
        if(StringUtils.isNotBlank(paramStr)){
            urlHander = urlHander + "?" + paramStr;
        }
        try {
            URL url = new URL(urlHander);
            //System.out.println("url:"+url);
            conn = createConnection(url,conn,false);
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
//            if(null != conn){
//                conn.disconnect();
//            }
        }
        return is;
    }

    private String createEncodeUrlByParams(HashMap<String,String> params){
        StringBuffer sb = new StringBuffer();
        Set<String> set = params.keySet();
        for (String s:set) {
            try {
                sb.append(s + "=" + URLEncoder.encode(params.get(s).toString(),"UTF-8") + "&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if(StringUtils.isNotBlank(sb)){
            sb.deleteCharAt(sb.length()-1);
        }
        //System.out.println(sb.toString());
        return sb.toString();
    }
    private HttpURLConnection createConnection(URL url,HttpURLConnection conn,boolean isPost){
        try {
            conn = (HttpURLConnection) url.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setUseCaches(false);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(false);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            if(isPost){
                // 发送POST请求必须设置如下两行
                conn.setRequestMethod("POST");
            }else{
                conn.setRequestMethod("GET");
            }
            conn.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return conn;
    }
    private String getDataStringByInputStream(InputStream is){
        BufferedReader reader = null;
        String rs = null;
        try {
            //获取并解析数据
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return rs;
    }

    public String httpClientPost( String url, Object objMessage) throws IOException {
        Gson gson = new Gson();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(gson.toJson(objMessage), "utf-8"));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        return resp;
    }
}
